﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CoolERP_BLL;
using CoolERP_Entities;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Text;
using CoolERP_Common;

namespace CoolERP_Web.User
{
    public partial class Organization : BasePage
    {
        //定义组织结构树深度常量
        private const int ROOT = 0;//公司级别
        private const int FurnitureFactory = 1;//家具厂级别
        private const int Department = 2;//部门级别
        private const int Workshop = 3;//车间级别
        private const int Position = 4;//职位级别
        private const int Staff = 5;//员工级别    
        private string[] DepPathList = null;
        private int SelDepth
        {
            get { return ViewState["SelDepth"] == null ? 0 : Convert.ToInt32(ViewState["SelDepth"]); }
            set { ViewState["SelDepth"] = value; }
        }
        private int iStatus
        {
            get { return this.ViewState["iStatus"] == null ? 0 : Convert.ToInt32(this.ViewState["iStatus"]); }
            set { this.ViewState["iStatus"] = value; }
        }
        protected Guid nowDepartmentId
        {
            get { return this.ViewState["nowDepartmentId"] == null ? Guid.Empty : new Guid(this.ViewState["nowDepartmentId"].ToString()); }
            set { this.ViewState["nowDepartmentId"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (this.GetUrlParam("id") != null)
                {
                    nowDepartmentId = Guid.Parse(this.GetUrlParam("id").ToString());
                    iStatus = 1;
                    using (DepartmentsBLL depB = new DepartmentsBLL())
                    {
                        Departments entity = depB.GetEntity(t => t.Id == nowDepartmentId);
                        if (!string.IsNullOrEmpty(entity.Path))
                            DepPathList = entity.Path.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    this.AjaxWebJavaScript("selTag($('.tags').find('li').eq(2));");
                }                
                InitRoot();
                if (DepPathList != null)//从用户编辑页面返回时展开树
                {
                    for (int i = 1; i < DepPathList.Count(); i++)
                    {
                        foreach (TreeNode node in tvZZJG.Nodes)
                        {
                            if (node.Value == DepPathList[i])
                            {
                                LoadChildNode(node);
                                break;
                            }
                        }
                    }
                }
                BindGridView();
            }
        }

        protected void LinkButton_Command(object sender, CommandEventArgs e)
        {
            iStatus = Convert.ToInt32(e.CommandArgument);
            this.AspNetPager1.CurrentPageIndex = 1;
            GridView1.ShowFooter = false;
            BindGridView();
        }

        #region======TreeView处理======
        protected void tvZZJG_SelectedNodeChanged(object sender, EventArgs e)
        {
            SelDepth = tvZZJG.SelectedNode.Depth;
            nowDepartmentId = Guid.Parse(tvZZJG.SelectedNode.Value);
            iStatus = 0;
            BindGridView();
            GridView1.EditIndex = -1;
            GridView1.ShowFooter = false;
        }

        private void InitRoot()
        {
            TreeNode root = new TreeNode();
            using (DepartmentsBLL depB = new DepartmentsBLL())
            {
                Departments entity = depB.GetEntity(c => c.ParentId == null);
                if (entity == null)
                {
                    root.Text = "所有";
                    root.Value = Guid.Empty.ToString();
                    nowDepartmentId = Guid.Empty;
                }
                else
                {
                    root.Text = entity.Name;
                    root.Value = entity.Id.ToString();
                    root.Expand();
                    if (nowDepartmentId == Guid.Empty)
                        nowDepartmentId = entity.Id;
                }
                root.ImageUrl = "../Images/Icon/home.png";
                tvZZJG.Nodes.Add(root);
            }
            LoadChildNode(root);
        }

        private void LoadChildNode(TreeNode node)
        {
            LoadUsers(node);
            using (DepartmentsBLL depB = new DepartmentsBLL())
            {
                List<Departments> depList = depB.GetList(c => c.ParentId == Guid.Parse(node.Value), "Code");
                foreach (Departments dept in depList)
                {
                    TreeNode child = new TreeNode();
                    child.Text = dept.Name;
                    child.Value = dept.Id.ToString();

                    if (DepPathList != null && DepPathList.Contains(dept.Id.ToString()))
                        child.Expand();
                    if (!node.ChildNodes.Contains(child))
                        node.ChildNodes.Add(child);
                    LoadChildNode(child);
                }
            }
        }

        private void LoadUsers(TreeNode node)
        {
            using (UserInDepartmentsBLL usersB = new UserInDepartmentsBLL())
            {
                List<Users> usersList = usersB.GetUsersByDepartmentId(Guid.Parse(node.Value)).Select(t => t.Users).ToList();
                foreach (Users u in usersList)
                {
                    TreeNode child = new TreeNode();
                    child.Text = u.Name;
                    child.Value = u.Id.ToString();
                    child.PopulateOnDemand = true;
                    child.ImageUrl = "../Images/Icon/user.png";
                    child.Expanded = true;
                    node.ChildNodes.Add(child);
                }
            }
        }
        #endregion

        #region=======GridView处理=======
        private void BindGridView()
        {
            int RecordCount = 0;
            if (iStatus == 0)
            {
                GridView1.Visible = true;
                GridView2.Visible = false;
                using (DepartmentsBLL depB = new DepartmentsBLL())
                {
                    List<Departments> itemLists = depB.GetPagerList(c => c.ParentId == nowDepartmentId, "Code", this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out RecordCount);
                    GridView1.DataSource = itemLists;
                    GridView1.DataBind();
                    if (itemLists.Count <= 0)
                        Utility.RenderEmptyGridView(GridView1, "Id,Code,Name,Description");
                }
            }
            else
            {
                this.GridView2.Visible = true;
                this.GridView1.Visible = false;
                using (UserInDepartmentsBLL usersB = new UserInDepartmentsBLL())
                {
                    List<Users> usersList = usersB.GetUsersByDepartmentId(t => t.DepartmentId == nowDepartmentId, "UserId", this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out RecordCount).Select(t => t.Users).ToList();
                    GridView2.DataSource = usersList;
                    GridView2.DataBind();
                }
            }
            this.AspNetPager1.RecordCount = RecordCount;
            this.AspNetPager1.Visible = RecordCount > 0;
            panMsg.Visible = !this.AspNetPager1.Visible;
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Departments entity = e.Row.DataItem as Departments;
                Literal liZN = e.Row.FindControl("liZN") as Literal;
                DropDownList ddl = e.Row.FindControl("ddlZN") as DropDownList;
                string keyVal = string.Empty;
                if (entity !=null && !string.IsNullOrEmpty(entity.Key))
                    keyVal = entity.Key.Split('_')[1];
                if (!string.IsNullOrEmpty(keyVal))
                {
                    if (liZN != null)
                        liZN.Text = EnumHelper.GetDescriptionByName(typeof(EnumDepartment), keyVal);
                    else
                        liZN.Text = "";
                }
                if (ddl != null)
                {
                    BindDDL(ddl);
                    if (!string.IsNullOrEmpty(keyVal) && ddl.Items.FindByValue(keyVal) != null)
                        ddl.SelectedValue = keyVal;
                }
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList ddl = e.Row.FindControl("ddlZN") as DropDownList;
                if (ddl != null)
                    BindDDL(ddl);
            }
        }

        private void BindDDL(DropDownList control)
        {
            control.Items.Clear();
            using (SystemParamBLL sBLL = new SystemParamBLL())
            {
                control.DataSource = sBLL.GetList(t => t.key.StartsWith("Department"));
                control.DataTextField = "value";
                control.DataValueField = "key";
                control.DataBind();
            }
            control.Items.Insert(0, new ListItem("无", ""));
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindGridView();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindGridView();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            TextBox txtCode = GridView1.Rows[e.RowIndex].FindControl("txtCode") as TextBox;
            TextBox txtName = GridView1.Rows[e.RowIndex].FindControl("txtName") as TextBox;
            DropDownList ddl = GridView1.Rows[e.RowIndex].FindControl("ddlZN") as DropDownList;
            TextBox txtDescription = GridView1.Rows[e.RowIndex].FindControl("txtDescription") as TextBox;
            Guid id = new Guid(GridView1.DataKeys[e.RowIndex].Value.ToString());
            int result = 0;
            using (DepartmentsBLL dBLL = new DepartmentsBLL())
            {
                Departments entity = dBLL.GetEntity(t => t.Id == id);
                entity.Code = txtCode.Text.Trim();
                entity.Name = txtName.Text.Trim();
                entity.Key = ddl.SelectedValue;
                entity.Description = txtDescription.Text.Trim();
                result = dBLL.SaveEntity(entity, t => t.Id != entity.Id && t.ParentId == entity.ParentId &&( t.Name == entity.Name || t.Code == entity.Code));
            }
            if (result == 1)
            {
                ShowMessage("修改成功", Request.ServerVariables["HTTP_REFERER"]);
            }
            else if (result == -1)
                ShowMessage("保存失败！您修改的部门编号或名称已存在，不能修改！");
            else
                ShowMessage("保存失败");
            GridView1.EditIndex = -1;
            BindGridView();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int childCount = 0;
            Guid delDepId = Guid.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
            using (DepartmentsBLL depB = new DepartmentsBLL())
            {
                List<Departments> childrenList = depB.GetList(t => t.ParentId == delDepId);
                childCount = childrenList.Count;
                if (childCount == 0)    //判断当前要删除部门是否有子部门，如果没有，可以删，如果有，则不可删
                {
                    Departments depDepEntity = depB.GetEntity(t => t.Id == delDepId);
                    try
                    {
                        if(depB.Delete(depDepEntity))
                            ShowMessage("删除成功", Request.ServerVariables["HTTP_REFERER"]);
                    }
                    catch (Exception ex)
                    {
                        ShowMessage("系统错误，删除失败！");
                    }
                }
                else      //有子部门的情况
                {
                    ShowMessage("您要删除的部门还有子部门，请确保它没子部门后再删除！");
                }
            }
            GridView1.EditIndex = -1;
            BindGridView();
        }

        protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string userId = GridView2.DataKeys[e.RowIndex].Value.ToString();
            using (UsersBLL uBLL = new UsersBLL())
            {
                if (uBLL.Deletes("Id", userId))
                    ShowMessage("删除成功", Request.ServerVariables["HTTP_REFERER"]);
                else
                    ShowMessage("删除出错");
            }
            BindGridView();
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGridView();
        }
        #endregion

        //判断当前结点是否为用户
        private bool IsUser()
        {
            using (UsersBLL usersB = new UsersBLL())
            {
                List<Users> temp = usersB.GetList(t => t.Id == nowDepartmentId);
                if (temp.Count > 0) 
                    return true;
                else 
                    return false;
            }
        }

        //新增按钮响应事件
        protected void AddImageButton_Click(object sender, ImageClickEventArgs e)
        {
            if (!IsUser())
            {
                if (iStatus == 0) //新增部门
                {
                    GridView1.ShowFooter = true;
                    BindGridView();
                }
                else //新增用户
                {
                    Response.Redirect("~/User/User_Edit.aspx?depId=" + nowDepartmentId.ToString());
                }
            }
            else
            {
                ShowMessage("当前结点为用户，不能新增任何组织！");
                return;
            }
        }

        //新增部门时，保存按钮响应事件
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            Guid newDepId = Guid.NewGuid();
            TextBox txtCode = GridView1.FooterRow.FindControl("txtCode") as TextBox;
            TextBox txtName = GridView1.FooterRow.FindControl("txtName") as TextBox;
            DropDownList ddl = GridView1.FooterRow.FindControl("ddlZN") as DropDownList;
            TextBox txtDescription = GridView1.FooterRow.FindControl("txtDescription") as TextBox;
            int result = 0;
            using (DepartmentsBLL dBLL = new DepartmentsBLL())
            {
                Departments entity = new Departments();
                entity.Id = Guid.NewGuid();
                string Path = string.Empty;
                if (nowDepartmentId != Guid.Empty)
                {
                    Departments parent = dBLL.GetEntity(t => t.Id == nowDepartmentId);
                    Path = parent.ParentId == null ? parent.Id.ToString() : parent.Path;
                    entity.ParentId = nowDepartmentId;
                }
                else
                    entity.ParentId = null;
                if (string.IsNullOrEmpty(Path))
                    entity.Path = entity.Id.ToString();
                else
                    entity.Path = string.Format("{0},{1}", Path, entity.Id);
                entity.Code = txtCode.Text.Trim();
                entity.Name = txtName.Text.Trim();
                entity.Key = ddl.SelectedValue;
                entity.Description = txtDescription.Text.Trim();
                //result = dBLL.SaveEntity(entity, t => t.Id != entity.Id && t.ParentId == entity.ParentId && (t.Name == entity.Name || t.Code == entity.Code));
            }
            if (result == 1)
            {
                ShowMessage("新增成功", Request.ServerVariables["HTTP_REFERER"]);
            }
            else if (result == -1)
                ShowMessage("保存失败！您新增的部门编号或名称已存在，不能修改！");
            else
                ShowMessage("保存失败");
            GridView1.ShowFooter = false;
            BindGridView();
        }

        //新增部门时，取消按钮响应事件
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            GridView1.ShowFooter = false;
            BindGridView();
        }
    }
}